<!-- 鼠标右击菜单 -->
<template>
  <div v-show="visible" class="right-click-menu" :style="{ left: `${x}px`, top: `${y}px` }">
    <div v-for="item in menus" :key="item.action" class="right-click-menu-item" @click="handleActionClick(item.action)">
      {{ item.text }}
    </div>
  </div>
</template>

<script>
export default {
  props: {
    // menu数据结构：[{ text: '修改', action: 'update' }]
    menus: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      visible: false,
      // 菜单位置
      x: 0,
      y: 0,
    }
  },
  methods: {
    handleActionClick(action) {
      this.$emit('select', action)
    },
    open(x, y) {
      // 每次显示都监听下一次“鼠标点击并释放”事件，以此来实现鼠标点击其他地方隐藏菜单
      addEventListener('mouseup', this.close)
      this.visible = true
      this.x = x
      this.y = y
    },
    close() {
      // 关闭时移除事件监听
      removeEventListener('mouseup', this.close)
      this.visible = false
    }
  }
}
</script>

<style scoped>
.right-click-menu {
  position: fixed;
  z-index: 10000;
  border-radius: 4px;
  width: 100px;
  height: auto;
  background: #fff;
  text-align: center;
  transition: all .3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  overflow: hidden;
}

.right-click-menu-item {
  padding: 5px;
  cursor: pointer;
}

.right-click-menu-item:hover {
  background: #e2e2e2;
}
</style>
